# -*- coding: UTF-8 -*-
import requests
import re
from pathlib import Path
from PySide6 import QtCore
from threading import Lock, Thread

from PySide6.QtGui import QPixmap, Qt, QDesktopServices
from PySide6.QtWidgets import (QVBoxLayout, QTextEdit, QPushButton,
                               QProgressBar, QFileDialog, QMessageBox, QDialog, QProgressDialog, QLabel, QHBoxLayout, QWidget)

current_version = "v2.0.3"
from Icon.icons import TUBIAO_WX, TUBIAO_windows


class HelpMenus:
    def __init__(self, main_window):
        self.main_window = main_window
        self.progress_dialog = None
        self.is_canceled = False
        self.cancel_lock = Lock()
        # 在初始化时自动检查更新
        QtCore.QTimer.singleShot(1000, self.check_update)  # 延迟1秒检查更新


    def download_update(self, download_link, save_path):
        if not self.validate_download_link(download_link):
            self.show_message_box('错误', '无效的下载链接。')
            return None

        try:
            response = requests.get(download_link, stream=True)

            if response.status_code == 200:
                total_size = int(response.headers.get('content-length', 0))
                if total_size == 0:
                    self.show_message_box('错误', '内容长度为零，无法下载。')
                    return None

                filename = Path(download_link).name
                file_path = save_path / filename
                downloaded_size = 0

                with open(file_path, 'wb') as f:
                    for chunk in response.iter_content(chunk_size=1024):
                        with self.cancel_lock:
                            if self.is_canceled:
                                return None

                        downloaded_size += len(chunk)
                        f.write(chunk)
                        progress = int((downloaded_size / total_size) * 100)

                        if self.progress_dialog is not None and self.progress_dialog.isVisible():
                            self.progress_dialog.setValue(progress)

                return file_path
            else:
                return None
        except Exception as e:
            self.show_message_box('错误', f"下载过程中发生错误: {str(e)}")
            return None

    def show_message_box(self, title, message):
        QMessageBox.information(self.main_window, title, message)

    def show_progress_dialog(self, maximum):
        self.progress_dialog = QProgressDialog("正在下载更新...请稍等！", None, 0, maximum, self.main_window)
        self.progress_dialog.resize(400, 100)
        self.progress_dialog.setWindowFlags(self.progress_dialog.windowFlags() | QtCore.Qt.WindowMinimizeButtonHint)

        self.progress_dialog.setWindowTitle("下载进度")
        self.progress_dialog.setWindowModality(QtCore.Qt.NonModal)
        self.progress_dialog.setAutoReset(False)
        self.progress_dialog.setAutoClose(False)

        # 获取对话框的布局
        self.progress_dialog.layout()

        # 获取进度条
        bar = self.progress_dialog.findChild(QProgressBar)

        # 设置进度条居中对齐
        bar.setAlignment(QtCore.Qt.AlignCenter)

        self.progress_dialog.show()

    def download_update_async(self, download_link):
        save_path = QFileDialog.getExistingDirectory(self.main_window, "选择保存路径")
        if save_path:
            thread = Thread(target=self._download_update_thread, args=(download_link, Path(save_path)))
            thread.start()
        else:
            self.show_message_box('错误', '未选择保存路径。')

    def _download_update_thread(self, download_link, save_path):
        self.is_canceled = False
        file_path = self.download_update(download_link, save_path)
        if file_path:
            self.show_message_box('更新', f"更新已下载完成，文件保存在：{file_path}, 请手动打开软件使用。")
        else:
            self.show_message_box('错误', '下载更新文件失败。')

    def check_update(self, auto_check=True):
        """检查更新
        
        Args:
            auto_check (bool): 是否为自动检查。如果是自动检查，则只在有更新时显示提示
        """
        try:
            response = requests.get(
                "https://www.xxx.com/config_latest_version.txt",
                timeout=5
            )
            if response.status_code == 200:
                version_info = response.text.splitlines()
                latest_version = version_info[0].strip()
                download_link = version_info[1].strip()
                update_content = "\n".join(version_info[2:])
                
                if latest_version > current_version:
                    reply = QMessageBox.question(
                        self.main_window, 
                        '更新提示', 
                        f"发现新版本 {latest_version}\n{update_content}\n\n点击'Yes'打开下载页面",
                        QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No
                    )
                    if reply == QMessageBox.StandardButton.Yes:
                        QDesktopServices.openUrl(QtCore.QUrl(download_link))
                elif not auto_check:  # 只在手动检查时显示"已是最新版本"的提示
                    self.show_message_box('更新', '当前已经是最新版本。')
            else:
                if not auto_check:  # 只在手动检查时显示错误信息
                    self.show_message_box('错误', f'检查更新失败。状态码: {response.status_code}')
        except requests.exceptions.ConnectionError as e:
            if not auto_check:
                self.show_message_box('错误', f"无法连接到更新服务器，请检查网络连接\n错误详情：{str(e)}")
        except requests.exceptions.Timeout:
            if not auto_check:
                self.show_message_box('错误', "连接更新服务器超时，请检查网络连接")
        except Exception as e:
            if not auto_check:
                self.show_message_box('错误', f"检查更新时发生错误：{str(e)}")

    def cancel_download(self):
        with self.cancel_lock:
            self.is_canceled = True
        if self.progress_dialog is not None and self.progress_dialog.isVisible():
            self.progress_dialog.close()

    def show_usage_instructions(self):
        # 创建对话框
        self.dialog = QDialog(self.main_window)
        self.dialog.setWindowTitle("注意事项")
        self.dialog.setFixedSize(460, 240)
        self.dialog.setModal(True)

        # 使用说明文本列表
        self.instructions_texts_1 = [
            "通用说明：\n",
            "1、标绿必填项",
            "2、设备信息Sheet的第一行是表头，不可删除，不可修改",
            "3、未填写数据的单元格最好不要留空，否则会提示未知厂商 None",
        ]
        self.instructions_texts_2 = [
            "设备信息：\n",
            "1、路由目的地址或者掩码不填，会生成默认路由",
            "2、下一跳地址可以为端口，但不建议",
            "3、SSH或者telnet填写其中1个协议，用户名和密码都是必填的",
            "4、新建用户名和密码需要根据不同厂商要求填写，比如英文大小写、数字组合",
            "5、用户名和密码长度为8-16位，密码需要包含大小写字母、数字和特殊符号",
            "6、enable密码为可选项，思科设备配置ssh时必填domin",
        ]

        self.instructions_texts_3 = [
            "管理vlan：\n",
            "1、标绿必填项",
            "2、同一台设备如果需要配置多个vlan地址，不同vlan分别填写",
            "3、如果管理vlan不填写，此行不会被生成"
        ]
        self.instructions_texts_4 = [
            "DHCP：\n",
            "1、标绿必填项",
            "2、如果DHCP地址池不填写，此行不会被生成",
            "3、网关和DNS可以都不填，也可以只填写其中1项",
            "4、如果生成DHCP的配置，同时也需要生成vlan或者端口的IP地址",
            "5、如果生成DNS配置，主DNS必填；备用DNS只在主DNS填写时才需要填写",
        ]
        # 创建大的文本框
        self.instructions_text_edit = QTextEdit()
        self.instructions_text_edit.setReadOnly(True)
        self.current_texts = self.instructions_texts_1
        self.update_text()

        # 设置单线边框样式
        self.instructions_text_edit.setStyleSheet("border: 1px solid black;")

        # 创建切换按钮
        self.toggle_button = QPushButton("切换")
        self.toggle_button.clicked.connect(self.toggle_text)

        # 设置布局
        layout = QVBoxLayout()
        layout.addWidget(self.instructions_text_edit)
        layout.addWidget(self.toggle_button)
        self.dialog.setLayout(layout)

        # 显示对话框
        self.dialog.exec()

    def toggle_text(self):
        # 切换文本
        if self.current_texts == self.instructions_texts_1:
            self.current_texts = self.instructions_texts_2
        elif self.current_texts == self.instructions_texts_2:
            self.current_texts = self.instructions_texts_3
        elif self.current_texts == self.instructions_texts_3:
            self.current_texts = self.instructions_texts_4
        else:
            self.current_texts = self.instructions_texts_1
        self.update_text()

    def update_text(self):
        # 更新文本框内容
        text = "\n".join(self.current_texts)
        self.instructions_text_edit.setPlainText(text)

    def create_replace_button_clicked_callback(self, text):
        return lambda: self.replace_text(text)

    def replace_text(self, text):
        self.main_window.mirrorLineEdit.setText(text)
        self.main_window.debug_page.mirror_edit.setText(text)

    def show_about_dialog(self):
        # 创建关于对话框
        about_dialog = QDialog(self.main_window)
        about_dialog.setWindowTitle("Netconfig.cloud")
        about_dialog.setFixedSize(300, 450)
        
        # 创建垂直布局
        layout = QVBoxLayout()
        
        # 添加腾讯会议图标
        logo_label = QLabel()
        pixmap = QPixmap()
        pixmap.loadFromData(bytes.fromhex(TUBIAO_windows))  # 使用您的图标数据
        pixmap = pixmap.scaled(80, 80, Qt.KeepAspectRatio)
        logo_label.setPixmap(pixmap)
        logo_label.setAlignment(Qt.AlignCenter)
        layout.addWidget(logo_label)
        
        # 添加版本号
        version_label = QLabel("V2.0.3")
        version_label.setAlignment(Qt.AlignCenter)
        layout.addWidget(version_label)
        
        # 添加按钮
        check_update_btn = QPushButton("检查更新")
        web_config_btn = QPushButton("Web版配置生成")
        standalone_btn = QPushButton("单机软件")
        feedback_btn = QPushButton("意见反馈")
        contact_btn = QPushButton("联系我们")
        instructions_btn = QPushButton("使用说明")
        
        # 连接按钮点击事件
        check_update_btn.clicked.connect(lambda: self.check_update(False))  # 手动检查更新
        web_config_btn.clicked.connect(lambda: QDesktopServices.openUrl(QtCore.QUrl("https://www.netconf.cloud/config")))  # 打开网页版
        standalone_btn.clicked.connect(lambda: QDesktopServices.openUrl(QtCore.QUrl("https://www.netconf.cloud/index/download/download.html")))  # 打开下载页面
        feedback_btn.clicked.connect(lambda: QDesktopServices.openUrl(QtCore.QUrl("https://f.wps.cn/ksform/w/write/7iVJAItY#routePromt")))  # 打开意见反馈表单
        contact_btn.clicked.connect(self.show_contact_dialog)  # 显示联系方式
        instructions_btn.clicked.connect(lambda: QDesktopServices.openUrl(QtCore.QUrl("https://uje456zh96.feishu.cn/wiki/UkpTwE9Fxibr3rk456ccMK6jnYg")))  # 打开意见反馈表单
        
        # 设置按钮样式
        button_style = """
        QPushButton {
            background-color: white;
            border: 1px solid #dcdcdc;
            border-radius: 4px;
            padding: 8px;
            margin: 5px;
        }
        QPushButton:hover {
            background-color: #f0f0f0;
        }
        """
        
        # 添加所有按钮到布局
        buttons = [
            check_update_btn,
            web_config_btn,
            standalone_btn,
            feedback_btn,
            contact_btn,
            # disclaimer_btn
            instructions_btn
        ]
        
        for btn in buttons:
            btn.setStyleSheet(button_style)
            layout.addWidget(btn)
        
        # 设置对话框布局
        about_dialog.setLayout(layout)
        
        # 显示对话框
        about_dialog.exec()

    def show_contact_dialog(self):
        """显示联系方式对话框"""
        contact_dialog = QDialog(self.main_window)
        contact_dialog.setWindowTitle("联系我们")
        contact_dialog.setFixedSize(400, 200)
        
        # 创建水平布局
        layout = QHBoxLayout()
        
        # 左侧二维码
        qr_label = QLabel()
        pixmap = QPixmap()
        pixmap.loadFromData(bytes.fromhex(TUBIAO_WX))  # 使用微信二维码图标
        pixmap = pixmap.scaled(150, 150, Qt.KeepAspectRatio)
        qr_label.setPixmap(pixmap)
        
        # 右侧信息
        info_widget = QWidget()
        info_layout = QVBoxLayout()
        
        # 添加官网链接
        website_title = QLabel("官方网站：")
        website_title.setStyleSheet("font-weight: bold;")
        website_link = QLabel('<a href="https://www.netconf.cloud">www.netconf.cloud</a>')
        website_link.setOpenExternalLinks(True)
        
        # 添加邮箱链接
        email_title = QLabel("联系邮箱：")
        email_title.setStyleSheet("font-weight: bold;")
        email_link = QLabel('<a href="mailto:1510756862@qq.com">1510756862@qq.com</a>')
        email_link.setOpenExternalLinks(True)
        
        info_layout.addWidget(website_title)
        info_layout.addWidget(website_link)
        info_layout.addSpacing(10)  # 添加一些垂直间距
        info_layout.addWidget(email_title)
        info_layout.addWidget(email_link)
        info_layout.addStretch()  # 添加弹性空间
        info_widget.setLayout(info_layout)
        
        # 添加到主布局
        layout.addWidget(qr_label)
        layout.addWidget(info_widget)
        
        contact_dialog.setLayout(layout)
        contact_dialog.exec()

    def show_disclaimer(self):
        # 创建对话框
        self.dialog = QDialog(self.main_window)
        self.dialog.setWindowTitle("免责声明")
        self.dialog.setFixedSize(460, 240)
        self.dialog.setModal(True)

        # 免责声明文本
        disclaimer_text = [
            "免责声明：\n",
            "1、本软件仅供学习和研究使用，不得用于任何商业用途。",
            "2、使用本软件所造成的任何后果，开发者不承担任何责任。",
            "3、用户应自行承担使用本软件的风险，并确保遵守相关法律法规。",
            "4、本软件的任何更新和修改，开发者保留最终解释权。",
            "5、用户对于在生产环境中使用该工具的决定需自行承担风险，开发者不对由于配置问题导致的任何损失负责。",
            "6、用户使用本软件即视为同意本声明。"
        ]

        # 创建大的文本框
        self.disclaimer_text_edit = QTextEdit()
        self.disclaimer_text_edit.setReadOnly(True)
        self.disclaimer_text_edit.setPlainText("\n".join(disclaimer_text))

        # 设置单线边框样式
        self.disclaimer_text_edit.setStyleSheet("border: 1px solid black;")

        # 设置布局
        layout = QVBoxLayout()
        layout.addWidget(self.disclaimer_text_edit)
        self.dialog.setLayout(layout)

        # 显示对话框
        self.dialog.exec()
